package com.chaoxing.service;

import com.chaoxing.config.ChaoXingConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
public class NotificationService {
    
    @Autowired(required = false)
    private JavaMailSender mailSender;
    
    @Autowired
    private ChaoXingConfig config;
    
    private final OkHttpClient httpClient = new OkHttpClient();
    
    public void sendNotification(String title, String content) {
        if (!config.getNotification().isEnabled()) {
            return;
        }
        
        log.info("发送通知: {} - {}", title, content);
        
        // 发送邮件通知
        if (mailSender != null && config.getNotification().getEmail().getTo() != null) {
            sendEmail(title, content);
        }
        
        // 发送Server酱通知
        if (config.getNotification().getServerChan().isEnabled() 
                && config.getNotification().getServerChan().getKey() != null) {
            sendServerChan(title, content);
        }
    }
    
    private void sendEmail(String subject, String text) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(config.getNotification().getEmail().getTo());
            message.setSubject("学习通自动签到 - " + subject);
            message.setText(text + "\n\n时间: " + new java.util.Date());
            
            mailSender.send(message);
            log.info("邮件通知发送成功");
        } catch (Exception e) {
            log.error("邮件通知发送失败", e);
        }
    }
    
    private void sendServerChan(String title, String content) {
        try {
            String url = "https://sctapi.ftqq.com/" + config.getNotification().getServerChan().getKey() + ".send";
            
            FormBody formBody = new FormBody.Builder()
                    .add("title", title)
                    .add("desp", content)
                    .build();
            
            Request request = new Request.Builder()
                    .url(url)
                    .post(formBody)
                    .build();
            
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    log.info("Server酱通知发送成功");
                } else {
                    log.error("Server酱通知发送失败: {}", response.code());
                }
            }
        } catch (IOException e) {
            log.error("Server酱通知发送异常", e);
        }
    }
}